package com.icesoft.core.common.configurer;

import com.icesoft.core.common.helper.lock.base.ICacheLockGroup;
import com.icesoft.core.common.helper.lock.impl.MemoryCacheLockGroupImpl;
import com.icesoft.core.common.helper.uid.UidGenerate;
import com.icesoft.core.common.helper.uid.impl.SingleUidGenerateImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.task.TaskSchedulerBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.concurrent.Executor;

@Configuration(proxyBeanMethods = false)
@Slf4j
@Order
public class DefaultCoreConditionBeanConfig {

    @Bean
    @ConditionalOnMissingBean(value = {TaskScheduler.class, Executor.class})
    public ThreadPoolTaskScheduler taskScheduler(ObjectProvider<TaskSchedulerBuilder> builderObjectProvider) {
        TaskSchedulerBuilder builder = builderObjectProvider.getIfAvailable(TaskSchedulerBuilder::new);
        ThreadPoolTaskScheduler taskScheduler = builder.build();
        if (taskScheduler.getPoolSize() == 1) { // 默认核心线程数：1
            taskScheduler.setPoolSize(Runtime.getRuntime().availableProcessors());
        }
        log.info("ThreadPoolTaskScheduler 核心线程数：{}", taskScheduler.getPoolSize());
        taskScheduler.setRemoveOnCancelPolicy(true);
        taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
        taskScheduler.setAwaitTerminationSeconds(5);
        taskScheduler.setThreadNamePrefix("BCAsync-");
        return taskScheduler;
    }

    @ConditionalOnBean(ThreadPoolTaskScheduler.class)
    @Bean
    public DefaultPoolAsyncConfigurer defaultPoolAsyncConfigurer(ThreadPoolTaskScheduler taskScheduler) {
        return new DefaultPoolAsyncConfigurer(taskScheduler);
    }

    @Bean
    @ConditionalOnMissingBean
    public ICacheLockGroup cacheLockGroup() {
        return new MemoryCacheLockGroupImpl();
    }

    @Bean
    @ConditionalOnMissingBean
    public static UidGenerate uidGenerate() {
        return new SingleUidGenerateImpl();
    }
}
